package com.numberone.master.modules.oa.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.numberone.master.common.persistence.Page;
import com.numberone.master.common.service.CrudService;
import com.numberone.master.common.utils.DateUtils;
import com.numberone.master.common.utils.StringUtils;
import com.numberone.master.modules.api.dao.ApiWorkOrderDao;
import com.numberone.master.modules.api.entity.ApiAttach;
import com.numberone.master.modules.oa.dao.DelayedDao;
import com.numberone.master.modules.oa.dao.WorkOrderDao;
import com.numberone.master.modules.oa.entity.Delayed;
import com.numberone.master.modules.oa.entity.Operation;
import com.numberone.master.modules.oa.entity.ProcessingFlow;
import com.numberone.master.modules.oa.entity.WorkOrder;
import com.numberone.master.modules.oa.util.PostUtil;
import com.numberone.master.modules.sys.entity.User;


@Service
@Transactional(readOnly = true)
public class WorkOrderService extends CrudService<WorkOrderDao, WorkOrder> {
	
	@Autowired
	private DelayedDao delayedDao;
	@Autowired
	private ApiWorkOrderDao apiWorkOrderDao;
	
	public WorkOrder get(String id) {
		return dao.get(id);
	}

	public Page<WorkOrder> findList(Page<WorkOrder> page,WorkOrder workOrder) {
		workOrder.setPage(page);
		page.setList(dao.findList(workOrder));
		return page;
	}
	
	public List<WorkOrder> homeList(WorkOrder workOrder){
		return dao.findList(workOrder);
	}

	public Page<WorkOrder> findAllList(Page<WorkOrder> page, String id,WorkOrder workOrder) {
		workOrder.setPage(page);
		if (workOrder.getBeginDate() == null){
			workOrder.setBeginDate(DateUtils.setDays(DateUtils.parseDate(DateUtils.getDate()), 1));
		}
		if (workOrder.getEndDate() == null){
			workOrder.setEndDate(DateUtils.addMonths(workOrder.getBeginDate(), 1));
		}
		page.setList(dao.findAllList(workOrder));
		return page;
	}
	
	public Page<WorkOrder> findPoolList(Page<WorkOrder> page, WorkOrder workOrder) {
		workOrder.setPage(page);
		if (workOrder.getBeginDate() == null){
			workOrder.setBeginDate(DateUtils.setDays(DateUtils.parseDate(DateUtils.getDate()), 1));
		}
		if (workOrder.getEndDate() == null){
			workOrder.setEndDate(DateUtils.addMonths(workOrder.getBeginDate(), 1));
		}
		page.setList(dao.findPoolList(workOrder));
		return page;
	}
	
	@Transactional(readOnly = false)
	public void update(WorkOrder workOrder) {
		dao.update(workOrder);
	}
	
	@Transactional(readOnly = false)
	public void updateReply(WorkOrder workOrder) {
		dao.updateReply(workOrder);
	}
	
	@Transactional(readOnly = false)
	public void updateFiles(WorkOrder workOrder) {
		
		String fileUrl = workOrder.getFiles();
		String[] fileArr = fileUrl.split("\\|");
		String serialNo = workOrder.getSerialNo();
		List<ApiAttach> atts = dao.findAttachBySeriaNo(serialNo);
		List<String> list = new ArrayList<String>();
		for (ApiAttach apiAttach : atts) {
			if(apiAttach.getAttachType().equals("2")){
				dao.deleteAttach(apiAttach.getId());
			}else{
				list.add(apiAttach.getAttachName());
			}
		}
		
		for (String file : fileArr) {
			String[] fileName = file.split("/");
			String fileNames = fileName[fileName.length-1] ;
			if(!list.contains(fileNames)&&!fileNames.equals("")){
				ApiAttach att = new ApiAttach();
				att.setAttachName(fileNames);
				att.setAttachPath(file.substring(10));
				att.setAttachType("2");
				att.setSerialNo(serialNo);
				dao.insertAttach(att);
			}
		}
		dao.updateFiles(workOrder);
	}
	
	/**
	 * 获得工单的object数据的Json
	 * @param wo
	 * @param currentUser
	 * @return
	 */
	public JSONObject getWoObj(WorkOrder wo, User currentUser){
		Date date = new Date();
		JSONObject obj = new JSONObject();
		JSONArray attachRef = new JSONArray();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = formatter.format(date);
		obj.put("sheetType", "056");
		obj.put("serviceType", wo.getServiceType());
		obj.put("serialNo", wo.getSerialNo());
		obj.put("serSupplier", wo.getSuggestion());
		obj.put("serCaller", wo.getSerCaller());
		obj.put("serCaller", wo.getSerCaller());
		obj.put("callerPwd", wo.getCallerPwd());
		obj.put("callTime", wo.getCallTime());
		obj.put("opPerson", currentUser.getName());
		obj.put("opCorp", currentUser.getOffice().getName());
		obj.put("opDepart", currentUser.getOffice().getName());
		obj.put("opContact", currentUser.getMobile());
		obj.put("opTime", dateString);
	
		obj.put("attachRef", attachRef);
		return obj;
	}
	
	/**
	 * 回复工单的Object
	 * @param wo
	 * @param currentUser
	 * @return
	 */
	public JSONObject getWoObj2(WorkOrder wo, User currentUser){
		Date date = new Date();
		JSONObject obj = new JSONObject();
		JSONArray attachRef = new JSONArray();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = formatter.format(date);
		obj.put("sheetType", "056");
		obj.put("serviceType", wo.getServiceType());
		obj.put("serialNo", wo.getSerialNo());
		obj.put("serSupplier", wo.getSuggestion());
		obj.put("serCaller", wo.getSerCaller());
		obj.put("serCaller", wo.getSerCaller());
		obj.put("callerPwd", wo.getCallerPwd());
		obj.put("callTime", wo.getCallTime());
		obj.put("opPerson", currentUser.getName());
		obj.put("opCorp", currentUser.getOffice().getName());
		obj.put("opDepart", currentUser.getOffice().getName());
		obj.put("opContact", currentUser.getMobile());
		obj.put("opTime", dateString);
		JsonConfig jsonConfig = new JsonConfig();
		jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
		
		/*String fileUrls = wo.getFiles();
		if(!StringUtils.isEmpty(fileUrls)){
			String[] fileArr = fileUrls.split("\\|");
			fileArr = ArrayUtils.remove(fileArr,0);
			for (String file : fileArr) {
				JSONObject attJson = new JSONObject();
				String[] fileUrl = file.split("/");
				attJson.put("attachName", fileUrl[fileUrl.length-1]);
				attJson.put("attachPath", file.substring(10));
				attJson.put("attachSize", "");
				attachRef.add(attJson,jsonConfig);
			}
		}*/
		
		List<ApiAttach> attachList = dao.findAttachBySeriaNo(wo.getSerialNo());
	 	for (ApiAttach apiAttach : attachList) {
	 		if(apiAttach.getAttachType().equals("2")){
	 			JSONObject attJson = new JSONObject();
				attJson.put("attachName", apiAttach.getAttachName());
				attJson.put("attachPath", apiAttach.getAttachPath());
				attJson.put("attachSize", apiAttach.getAttachSize());
				attachRef.add(attJson,jsonConfig);
	 		}
		}
		obj.put("attachRef", attachRef);
		return obj;
	}
	
	/**
	 * 阶段回复
	 * @param workOrder
	 * @param currentUser
	 * @return
	 */
	public boolean stageReply(WorkOrder workOrder, User currentUser) {
		JSONObject woJson = new JSONObject();
		JSONObject objJson = this.getWoObj(workOrder,currentUser);
		JSONObject parJson = new JSONObject();
		parJson.put("StepResult", workOrder.getResult());
		List<Delayed> delayeds = delayedDao.findByWoId(workOrder.getId());
		if(delayeds.size()!=0){
			int extendDate = 0;
			parJson.put("isDeferReploy", "是");
			parJson.put("isDeferReploy", "是");
			for (Delayed delayed : delayeds) {
				if(!StringUtils.isEmpty(delayed.getExtendDate())){
					int a = Integer.parseInt(delayed.getExtendDate());
					extendDate += a;
				}
			}
			parJson.put("delayTime", "共延时"+extendDate+"小时。");
		}
		parJson.put("isDeferReploy", "否");
		parJson.put("puzzleComplain", "否");
		parJson.put("delayTime", "0");
		parJson.put("opTypeCd", workOrder.getOpTypeCd());
		parJson.put("provCode", workOrder.getProvCode());
		parJson.put("tenantId", workOrder.getTenantId());
		woJson.put("object", objJson);
		woJson.put("params", parJson);
		String url = apiWorkOrderDao.getApiUrlByName("stageReply");
		String rtn = PostUtil.httpPostWithJson(woJson, url);
		JSONObject rtnJson = JSONObject.fromObject(rtn);
		String rtnCode = rtnJson.getString("rtnCode");
		if(!StringUtils.isEmpty(rtnCode)){
			if(rtnCode.equals("0")){
				return true;
			}
			return false;
		}
		return false;
	}
	
	/**
	 * 回复
	 * @param workOrder
	 * @param currentUser
	 * @return
	 */
	public boolean reply(WorkOrder workOrder, User currentUser) {
		JSONObject woJson = new JSONObject();
		JSONObject objJson = this.getWoObj2(workOrder,currentUser);
		JSONObject parJson = new JSONObject();
		parJson.put("ndeptContact", currentUser.getName());
		parJson.put("ndeptContactPhone", currentUser.getMobile());
		parJson.put("compProp", workOrder.getCompProp());
		parJson.put("isReplied", workOrder.getIsReplied());
		parJson.put("issueEliminatTime", workOrder.getIssueEliminatTime());
		parJson.put("issueEliminatReason", workOrder.getIssueEliminatReason());
		parJson.put("dealDesc", workOrder.getDealDesc());
		parJson.put("dealResult", workOrder.getDealResult());
		parJson.put("provCode", workOrder.getProvCode());
		parJson.put("tenantId", workOrder.getTenantId());
		woJson.put("object", objJson);
		woJson.put("params", parJson);
		String url = apiWorkOrderDao.getApiUrlByName("reply");
		String rtn = PostUtil.httpPostWithJson(woJson, url);
		logger.debug("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"+rtn);
		System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"+rtn);
		JSONObject rtnJson = JSONObject.fromObject(rtn);
		String rtnCode = rtnJson.getString("rtnCode");
		if(!StringUtils.isEmpty(rtnCode)){
			if(rtnCode.equals("0")){
				return true;
			}
			return false;
		}
		return false;
	}
	
	/**
	 * 驳回客服
	 * @param workOrder
	 * @param currentUser
	 * @return
	 */
	public boolean reject(WorkOrder workOrder, User currentUser) {
		JSONObject woJson = new JSONObject();
		JSONObject objJson = this.getWoObj(workOrder,currentUser);
		JSONObject parJson = new JSONObject();
		parJson.put("withdrawReason", workOrder.getResult());
		parJson.put("provCode", workOrder.getProvCode());
		parJson.put("tenantId", workOrder.getTenantId());
		woJson.put("object", objJson);
		woJson.put("params", parJson);
		String url = apiWorkOrderDao.getApiUrlByName("reject");
		String rtn = PostUtil.httpPostWithJson(woJson, url);
		JSONObject rtnJson = JSONObject.fromObject(rtn);
		String rtnCode = rtnJson.getString("rtnCode");
		if(!StringUtils.isEmpty(rtnCode)){
			if(rtnCode.equals("0")){
				return true;
			}
			return false;
		}
		return false;
	}
	
	/**
	 * 领取工单（确认受理）
	 * @param workOrder
	 * @param currentUser
	 * @return
	 */
	public boolean receive(WorkOrder workOrder, User currentUser) {
		JSONObject woJson = new JSONObject();
		JSONObject objJson = this.getWoObj(workOrder,currentUser);
		JSONObject parJson = new JSONObject();
		parJson.put("confirmReason", "受理成功");
		parJson.put("provCode", workOrder.getProvCode());
		parJson.put("tenantId", workOrder.getTenantId());
		woJson.put("object", objJson);
		woJson.put("params", parJson);
		String url = apiWorkOrderDao.getApiUrlByName("receive");
		String rtn = PostUtil.httpPostWithJson(woJson, url);
		JSONObject rtnJson = JSONObject.fromObject(rtn);
		String rtnCode = rtnJson.getString("rtnCode");
		if(!StringUtils.isEmpty(rtnCode)){
			if(rtnCode.equals("0")){
				return true;
			}
			return false;
		}
		return false;
	}
	
	/**
	 * 确认撤单
	 * @param workOrder
	 * @param currentUser
	 * @return
	 */
	public boolean isRevoke(WorkOrder workOrder, User currentUser) {
		String cancelPerson = workOrder.getOpPerson();
		JSONObject woJson = new JSONObject();
		JSONObject objJson = this.getWoObj(workOrder,currentUser);
		JSONObject parJson = new JSONObject();
		parJson.put("cancelPerson", cancelPerson);
		parJson.put("cancelAdvice", workOrder.getCancelAdvice());
		parJson.put("provCode", workOrder.getProvCode());
		parJson.put("tenantId", workOrder.getTenantId());
		woJson.put("object", objJson);
		woJson.put("params", parJson);
		String url = apiWorkOrderDao.getApiUrlByName("isRevoke");
		String rtn = PostUtil.httpPostWithJson(woJson, url);
		JSONObject rtnJson = JSONObject.fromObject(rtn);
		String rtnCode = rtnJson.getString("rtnCode");
		if(!StringUtils.isEmpty(rtnCode)){
			if(rtnCode.equals("0")){
				return true;
			}
			return false;
		}
		return false;
	}
	
	/**
	 * 查询客服流程
	 * @param workOrder
	 * @param currentUser
	 * @return
	 */
	public List<ProcessingFlow> getProcessingFlow(WorkOrder workOrder, User currentUser){
		JSONObject woJson = new JSONObject();
		JSONObject objJson = this.getWoObj(workOrder,currentUser);
		JSONObject parJson = new JSONObject();
		parJson.put("outSystem", "BOMS");
		parJson.put("serialNo", workOrder.getCancelAdvice());
		parJson.put("workItemId", workOrder.getWorkItemId());
		parJson.put("provCode", workOrder.getProvCode());
		parJson.put("tenantId", workOrder.getTenantId());
		woJson.put("object", objJson);
		woJson.put("params", parJson);
		String url = apiWorkOrderDao.getApiUrlByName("getProcessingFlow");
		String rtn = PostUtil.httpPostWithJson(woJson, url);
		JSONObject rtnJson = JSONObject.fromObject(rtn);
		JSONArray pfArr = (JSONArray) rtnJson.get("beans");
		System.out.println(pfArr);
		String rtnCode = rtnJson.getString("rtnCode");
		if(!StringUtils.isEmpty(rtnCode) && pfArr!=null){
			if(rtnCode.equals("0")){
				@SuppressWarnings({ "deprecation", "unchecked" })
				List<ProcessingFlow> list = JSONArray.toList(pfArr, ProcessingFlow.class);
				return list;
			}
			return null;
		}		
		return null;
	}
	
	
	/**
	 * 追回
	 * @param workOrder
	 * @param currentUser
	 */
	@Transactional(readOnly = false)
	public String getBack(WorkOrder workOrder, User currentUser) {
		String useId = currentUser.getId();
		String state = workOrder.getState();
		Operation opr = dao.getLastNode(workOrder.getId());
		if("1".equals(state)||"2".equals(state)){
			if(opr.getOperationNo().equals(currentUser.getNo())){
				workOrder.setBelong(useId);
				dao.update(workOrder);
				return "追回成功";
			}else{
				return "追回失败";
			}
		}else{
			return "追回失败";
		}
		
	}

	/**
	 * 问题收集
	 * @param workOrder
	 * @param currentUser
	 * @return
	 */
	public boolean problemCollection(WorkOrder workOrder, User currentUser) {
		JSONObject woJson = new JSONObject();
		JSONObject objJson = this.getWoObj(workOrder,currentUser);
		JSONObject parJson = new JSONObject();
		parJson.put("confirmReason", "受理成功");
		parJson.put("provCode", workOrder.getProvCode());
		parJson.put("tenantId", workOrder.getTenantId());
		woJson.put("object", objJson);
		woJson.put("params", parJson);
		String url = apiWorkOrderDao.getApiUrlByName("problemCollection");
		String rtn = PostUtil.httpPostWithJson(woJson, url);
		JSONObject rtnJson = JSONObject.fromObject(rtn);
		String rtnCode = rtnJson.getString("rtnCode");
		if(!StringUtils.isEmpty(rtnCode)){
			if(rtnCode.equals("0")){
				return true;
			}
			return false;
		}
		return false;
	}

}
